﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OVS_FormsRecognition;
using OVS_ApplicationConfiguration;
using OVS.BLL;
using OVS.BusinessObjects;
using MjpegProcessor;
using System.Data.SqlClient;
using System.Collections.ObjectModel;
using System.Data;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using OVS_NotificationSender.Manager;
using OVS_VideoRecorder.Manager;
using OVS_TrajectoryCalculation.Manager;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using OVS_FormsRecognition.Objects;
using OVS_FormsRecognition.Manager;
using OVS_FrontOffice.Manager;
using OVS_NotificationSender;
using OVS_VideoRecorder;
using OVS_TrajectoryCalculation;
using OVS_Tools;
using System.Windows.Threading;
using System.Windows.Media.Animation;
using System.Diagnostics;
using System.Timers;
using System.Collections;

namespace OVS_FrontOffice
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Attributs
        List<String> toto = null;
        //Point startPoint;
        MjpegDecoder _mjpeg;
        Boolean Result_Connexion;
        Schedule sche;
        ObservableCollection<User> listUser;
        Storyboard storyboard;
        bool _started;
        int a = 1;
        public ObservableCollection<BoolStringClass> TheList { get; set; }
        public String Desciption, Localisation, Nom, Adresse;
        public Boolean utilisation_Cam;
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;
        List<ListView> listLv;
        List<CheckBox> listCk;
        public ObservableCollection<StatsData> lstStats { get; set; }
        private int SelectedCam = -1;


        private static readonly log4net.ILog _Log = log4net.LogManager.GetLogger(typeof(MainWindow));
        private List<Image_Haar> _listHaarObjects;
        private List<Camera> _listCameraForHaarTest;
        private MjpegDecoder mjpegForCurrentCamHaarTest;
        private static CameraFromMjpegDecoder camDecoderForTestHaarObjects;
        private bool CaptureIsStarted;

        public class BoolStringClass
        {
            public string TheText { get; set; }
            public int TheValue { get; set; }

            public bool IsSelected { get; set; }
        }
        #endregion

        public MainWindow()
        {


            InitializeComponent();
            //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEvent);
            _started = false;
            button_Ajouter_Cam.Resources["fontSizeTextBlock"] = (Double)12;
            button_Supprimer_Cam.Resources["fontSizeTextBlock"] = (Double)12;
            button_Tester_Cam.Resources["fontSizeTextBlock"] = (Double)12;
            button_Valider_Config_Mail.Resources["fontSizeTextBlock"] = (Double)12;
            button_Annuler_Config_Mail.Resources["fontSizeTextBlock"] = (Double)12;
            button_Modifier.Resources["fontSizeTextBlock"] = (Double)12;
            button_Supprimer_Config_Utilisateur.Resources["fontSizeTextBlock"] = (Double)12;
            button_Ajouter_Config_Utilisateur.Resources["fontSizeTextBlock"] = (Double)12;
            clearDb.Resources["fontSizeTextBlock"] = (Double)12;
            button_Ajouter_Fichier_Haar.Resources["fontSizeTextBlock"] = (Double)12;
            button_Update_Fichier_Haar.Resources["fontSizeTextBlock"] = (Double)12;
            button_Delete_Fichier_Haar.Resources["fontSizeTextBlock"] = (Double)12;
            listCk = new List<CheckBox>();
            this.DataContext = this;
            lstStats = new ObservableCollection<StatsData>();


            #region init Events
            minWin.MouseLeftButtonUp += new MouseButtonEventHandler(this.MINIMIZE);
            minWin.MouseEnter += new MouseEventHandler(this.EnterMin);
            minWin.MouseLeave += new MouseEventHandler(this.LeaveMin);
            maxWin.MouseLeftButtonUp += new MouseButtonEventHandler(this.MAX_RESTORE);
            maxWin.MouseEnter += new MouseEventHandler(this.EnterMax);
            maxWin.MouseLeave += new MouseEventHandler(this.LeaveMax);
            closeWin.MouseLeftButtonUp += new MouseButtonEventHandler(this.EXIT);
            closeWin.MouseEnter += new MouseEventHandler(this.EnterMax);
            closeWin.MouseLeave += new MouseEventHandler(this.LeaveMax);
            dockPanel1.MouseDown += new MouseButtonEventHandler(this.move_window);
            #endregion

            FormsRecognitionManager.Instance.UpdateCameraDetectionSenderEvent += new FormsRecognitionManager.UpdateCameraDetectionSenderEventHandler(CallBackUpdateCameraDetectionSenderEvent);

            FrontOfficeManager.Instance.RegisterEventHandlers();

#if DEBUG
            // affichage des IHM des modules pour les tests
            // InitModules(this.Top);
#endif



            startCapture();

            _mjpeg = new MjpegDecoder();
            _mjpeg.FrameReady += mjpeg_FrameReady;

            Récupérer_Toute_Camera_Dans_Base();

            //mais la config mail dans les champs
            List<Config> listConfig = ConfigBLL.Instance.GetConfigs();
            if (listConfig.Count > 0)
            {
                foreach (Config myConfig in listConfig)
                {
                    textBox_Adresse_Emission.Text = myConfig.conf_fn_mail;
                    textBox_Login_SMTP.Text = myConfig.conf_fn_log;
                    textBox_Pass_SMTP.Password = myConfig.conf_fn_pwd;
                    textBox_Serveur_SMTP.Text = myConfig.conf_fn_serv;

                }
            }

            //Recupération des utilisateurs dans la base
            Recuperer_Tout_User_Dans_Base();
            //if (ListCam.Items.Count != 0)
            //{
            //    System.Windows.Controls.Image image = (System.Windows.Controls.Image)ListCam.Items[0];
            //    ListCam.Height = image.Height;
            //}
            //else
            //    ListCam.Height = 80;

            #region add listview planif
            listLv = new List<ListView>();
            listLv.Add(lundi1);
            listLv.Add(lundi2);
            listLv.Add(lundi3);
            listLv.Add(mardi1);
            listLv.Add(mardi2);
            listLv.Add(mardi3);
            listLv.Add(mercredi1);
            listLv.Add(mercredi2);
            listLv.Add(mercredi3);
            listLv.Add(jeudi1);
            listLv.Add(jeudi2);
            listLv.Add(jeudi3);
            listLv.Add(vendredi1);
            listLv.Add(vendredi2);
            listLv.Add(vendredi3);
            listLv.Add(samedi1);
            listLv.Add(samedi2);
            listLv.Add(samedi3);
            listLv.Add(dimanche1);
            listLv.Add(dimanche2);
            listLv.Add(dimanche3);
            #endregion
            ListCam.SelectedItem = ListCam.Items[0];





        }

        private void UnhandledExceptionEvent(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show(" UnhandledExceptionEvent: " + e.ToString());

        }

        #region Configuration Caméras
        private void clearDb_Click(object sender, RoutedEventArgs e)
        {

            if (MessageBox.Show("Attention cette fonction requiert le lancement de l'appli depuis le serveur (si ce n'est pas le cas elle supprimera les infos en BDD mais pas les fichiers (videos et images)!!", "Attention", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                List<Alert> lstAlert = AlertBLL.Instance.GetAlerts();
                foreach (Alert tmpA in lstAlert)
                {
                    if (tmpA.aler_id == 1165 || tmpA.aler_id == 1166 || tmpA.aler_id == 1167 || tmpA.aler_id == 1168)
                    { }
                    else
                    {
                        if (System.IO.File.Exists(tmpA.aler_image_traj))
                        {
                            // Use a try block to catch IOExceptions, to
                            // handle the case of the file already being
                            // opened by another process.
                            try
                            {
                                System.IO.File.Delete(tmpA.aler_image_traj);
                            }
                            catch (System.IO.IOException ex)
                            {
                                MessageBox.Show(" clearDb_Click: " + ex.Message);
                            }
                        }
                        AlertBLL.Instance.RemoveAlert(tmpA);
                    }
                }
                List<Video> lstVidz = VideoBLL.Instance.GetVideos();
                foreach (Video tmpV in lstVidz)
                {
                    if (tmpV.vide_id == 212)
                    { }
                    else
                    {
                        if (System.IO.File.Exists(tmpV.vide_fn))
                        {
                            // Use a try block to catch IOExceptions, to
                            // handle the case of the file already being
                            // opened by another process.
                            try
                            {
                                System.IO.File.Delete(tmpV.vide_fn);
                            }
                            catch (System.IO.IOException ex)
                            {
                                MessageBox.Show(" clearDb_Click: " + ex.Message);
                            }
                        }
                        VideoBLL.Instance.RemoveVideo(tmpV);
                    }
                }
                List<Image_Details> lstImg = Image_DetailsBLL.Instance.GetImage_Detailss();
                foreach (Image_Details tmpI in lstImg)
                {
                    if (tmpI.imde_id == 727 || tmpI.imde_id == 728 || tmpI.imde_id == 729)
                    { }
                    else
                        Image_DetailsBLL.Instance.RemoveImage_Details(tmpI);
                }

            }



        }
        private void button_Tester_Cam_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (button_Tester_Cam.Text.ToString() == "Tester")
                {
                    this.button_Tester_Cam.Text = "Stop";
                    _mjpeg.ParseStream(new Uri(Adresse_Ip.Text));
                    this.label_Resultat_Test.Text = "Connexion réussi";
                    this.label_Resultat_Test.Foreground = new SolidColorBrush(Colors.Green);
                    Result_Connexion = true;
                }
                else if (button_Tester_Cam.Text.ToString() == "Stop")
                {
                    button_Tester_Cam.Text = "Tester";
                    _mjpeg.StopStream();
                }
            }
            catch (Exception ex)
            {
                button_Tester_Cam.Text = "Tester";
                this.label_Resultat_Test.Text = "Impossible de se connecter à la caméra!!!";
                this.label_Resultat_Test.Foreground = new SolidColorBrush(Colors.Red);
                Result_Connexion = false;
            }
        }
        public void CreateCheckBoxList(List<int> liste_image, int id_camera)
        {
            this.DataContext = null;

            bool check = false;

            TheList = new ObservableCollection<BoolStringClass>();

            foreach (int myImage in liste_image)
            {
                //on récupère l'Id de la photo
                Image_Haar uneImage = Image_HaarBLL.Instance.GetImage_Haar(myImage);

                //on recherche si pour cette image la caméra existe
                List<CameraImage_Haar> List_imgs = CameraImage_HaarBLL.Instance.GetCameraImage_HaarsOfCamera(id_camera);
                foreach (CameraImage_Haar myImg in List_imgs)
                {
                    if (myImg.Image_Haar_imha_id == uneImage.imha_id)
                    {
                        check = true;
                    }
                }


                TheList.Add(new BoolStringClass { IsSelected = check, TheText = "" + uneImage.imha_label + "              ", TheValue = uneImage.imha_id });
                //compteur++;
                check = false;
            }
            this.DataContext = this;

        }

        private void CheckBoxZone_Checked(object sender, RoutedEventArgs e)
        {


            CheckBox chkZone = (CheckBox)sender;

            CameraImage_Haar jointure = new CameraImage_Haar();

            List<int> Tab_Image = new List<int>();
            String Nom_Camera_List = list_Camera_Ip.SelectedItem.ToString();

            //on récupère l'Id de la caméra dans la table
            Camera UneCam = CameraBLL.Instance.GetCamera_By_Nom(Nom_Camera_List);

            jointure.Camera_came_id = UneCam.came_id;

            jointure.Image_Haar_imha_id = int.Parse(chkZone.Tag.ToString());


            // ZoneText.Text = "Selected Zone Name= " + chkZone.Content.ToString();
            // ZoneValue.Text = "Selected Zone Value= " + chkZone.Tag.ToString();
            try
            {
                if (chkZone.IsChecked == true)
                {
                    //ZoneValue2.Text = " Coché";
                    int test = CameraImage_HaarBLL.Instance.AddCameraImage_Haar2(jointure);
                    //ici afficher
                }
                else
                {
                    //ZoneValue2.Text = " décoché";
                    int test = CameraImage_HaarBLL.Instance.RemoveCameraImage_Haar(jointure);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("CheckBoxZone_Checked: " + ex.Message);
            }
        }

        private void mjpeg_FrameReady(object sender, FrameReadyEventArgs e)
        {
            imageBox_Capture_Camera.Source = e.BitmapImage;
        }

        private void button_Ajouter_Cam_Click(object sender, RoutedEventArgs e)
        {
            if (Result_Connexion == true)
            {

                //ouvir la fenetre pour indiquer le nom, la description et la localisation de la nouvelle caméra
                ApplicationConfigurationaddcamera _ApplicationConfigurationaddcameraView = new ApplicationConfigurationaddcamera();
                _ApplicationConfigurationaddcameraView.ShowDialog();

                if (_ApplicationConfigurationaddcameraView.DialogResult == true)
                {
                    // Read the contents of testDialog's TextBox.

                    Nom = _ApplicationConfigurationaddcameraView.textBox_Nom_Camera.Text;
                    Desciption = _ApplicationConfigurationaddcameraView.textBox_Description.Text;
                    Localisation = _ApplicationConfigurationaddcameraView.textBox_Localisation.Text;
                    Adresse = this.Adresse_Ip.Text;

                    if (_ApplicationConfigurationaddcameraView.checkBox_Activ_Camera.IsChecked == true)
                    {
                        utilisation_Cam = true;
                    }
                    else
                    {
                        utilisation_Cam = false;
                    }


                    Ajout_Camera_Dans_Base(Adresse);


                }
                else
                {
                    //appui sur annuler
                }

            }
            else
            {
                label_Resultat_Test.Text = " Impossible d'ajouter cette caméra car la connexion ne marche pas !";
                this.label_Resultat_Test.Foreground = new SolidColorBrush(Colors.Red);
            }
        }

        //Ajoute une camera dans la base de données si elle n'hexiste pas deja en base.
        private void Ajout_Camera_Dans_Base(String Adresse_Camera)
        {
            //si la camera n'héxiste pas alors l'entre dans la base de donnée.
            if (Verif_Si_Camera_Existe_Deja() == false)
            {

                list_Camera_Ip.Items.Add("" + Nom + "");


                Camera objCamera = new Camera();

                objCamera.came_desc = Desciption;
                objCamera.came_loc = Localisation;
                objCamera.came_nom = Nom;
                objCamera.came_url = Adresse;
                objCamera.came_use = utilisation_Cam;

                CameraBLL.Instance.AddCamera(objCamera);//ajoute l'objet en base


                label_Resultat_Test.Text = "Ajout de la caméra réussi réussi";
                this.label_Resultat_Test.Foreground = new SolidColorBrush(Colors.Green);
            }


        }

        private void Recuperation_Camera_existante_Dans_List()
        {
            //Récupération des caméra de la base de données + mise de ces éléments dans la listbox
        }

        private Boolean Verif_Si_Camera_Existe_Deja()
        {

            Boolean result = false;

            List<Camera> listCams = CameraBLL.Instance.GetCameras();//ajoute l'objet en base
            foreach (Camera myCam in listCams)
            {

                //list_Camera_Ip.Items.Add("" + myCam.came_nom + "");
                if (myCam.came_url == Adresse)
                {
                    result = true;

                    label_Resultat_Test.Text = "La caméra existe déja dans la base( " + myCam.came_nom + " )";
                    this.label_Resultat_Test.Foreground = new SolidColorBrush(Colors.Red);
                }


            }



            return result;
        }

        private void button_Supprimer_Cam_Click(object sender, RoutedEventArgs e)
        {
            //supression de la caméra séléctionnnée de la base de données
            try
            {
                CameraBLL.Instance.RemoveCamera_By_Nom(list_Camera_Ip.SelectedItem.ToString());

                //supression de l'item séléctionnée
                int itemselect = list_Camera_Ip.Items.IndexOf(list_Camera_Ip.SelectedItem);
                this.list_Camera_Ip.Items.RemoveAt(itemselect);

            }
            catch (Exception ex)
            {

                MessageBox.Show("Suppression caméra dans base: " + ex.Message);
            }

        }

        //recupération de toutes les camera en base de données.
        private void Récupérer_Toute_Camera_Dans_Base()
        {

            List<Camera> listCams = CameraBLL.Instance.GetCameras();
            foreach (Camera myCam in listCams)
            {
                list_Camera_Ip.Items.Add(myCam.came_nom);
            }
        }

        protected void HandleDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string element;
            element = list_Camera_Ip.SelectedItem.ToString();



            List<Camera> listCams = CameraBLL.Instance.GetCameras();
            foreach (Camera myCam in listCams)
            {
                if (myCam.came_nom == element)
                {
                    //ouvir la fenetre pour indiquer le nom, la description et la localisation de la nouvelle caméra
                    ApplicationConfigurationaddcamera _ApplicationConfigurationaddcameraView = new ApplicationConfigurationaddcamera();

                    _ApplicationConfigurationaddcameraView.textBox_Nom_Camera.Text = myCam.came_nom;
                    _ApplicationConfigurationaddcameraView.textBox_Description.Text = myCam.came_desc;
                    _ApplicationConfigurationaddcameraView.textBox_Localisation.Text = myCam.came_loc;
                    _ApplicationConfigurationaddcameraView.textBox_IP.Text = myCam.came_url;
                    Adresse = myCam.came_url;
                    _ApplicationConfigurationaddcameraView.Valider.Text = "Mettre à Jour";

                    if (myCam.came_use == true)
                    {
                        _ApplicationConfigurationaddcameraView.checkBox_Activ_Camera.IsChecked = true;
                    }


                    _ApplicationConfigurationaddcameraView.ShowDialog();


                    //si on clique sur le bouton ajouter
                    if (_ApplicationConfigurationaddcameraView.DialogResult == true)
                    {
                        // Read the contents of testDialog's TextBox.

                        Nom = _ApplicationConfigurationaddcameraView.textBox_Nom_Camera.Text;
                        Desciption = _ApplicationConfigurationaddcameraView.textBox_Description.Text;
                        Localisation = _ApplicationConfigurationaddcameraView.textBox_Localisation.Text;
                        Adresse = _ApplicationConfigurationaddcameraView.textBox_IP.Text;
                        //si la case esr cocher alors on mais vrai dans la variable dutilisation de la camera
                        if (_ApplicationConfigurationaddcameraView.checkBox_Activ_Camera.IsChecked == true)
                        {
                            _ApplicationConfigurationaddcameraView.checkBox_Activ_Camera.Content = "Checked";
                            utilisation_Cam = true;
                        }

                        Maj_Camera_Dans_Base(myCam.came_id);


                    }
                    else
                    {
                        //appui sur annuler
                    }
                }

            }

        }

        //provoque la selection des objets de la caméra selectioner puis les affiche dans la liste à coté
        private void list_Camera_Ip_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                List<int> Tab_Image = new List<int>();
                if (list_Camera_Ip.SelectedItem == null)
                {
                }
                else
                {
                    String Nom_Camera_List = list_Camera_Ip.SelectedItem.ToString();

                    //on récupère l'Id de la caméra dans la table
                    Camera UneCam = CameraBLL.Instance.GetCamera_By_Nom(Nom_Camera_List);


                    //Méthode qui récupère les objets à detecter dans la base
                    List<Image_Haar> listImages = Image_HaarBLL.Instance.GetImage_Haars();

                    foreach (Image_Haar myImage in listImages)
                    {
                        Tab_Image.Add(myImage.imha_id);
                        String echo = myImage.imha_label;
                    }


                    //Appel de la méthode qui génère la liste
                    CreateCheckBoxList(Tab_Image, UneCam.came_id);


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("list_Camera_Ip_SelectionChanged: " + ex.Message);
            }
        }

        private void Maj_Camera_Dans_Base(int Id)
        {
            Camera objCamera = new Camera();

            objCamera.came_id = Id;
            objCamera.came_desc = Desciption;
            objCamera.came_loc = Localisation;
            objCamera.came_nom = Nom;
            objCamera.came_url = Adresse;
            objCamera.came_use = utilisation_Cam;

            CameraBLL.Instance.UpdateCamera(objCamera);//ajoute l'objet en base

            //suppression de l'élément en cours
            list_Camera_Ip.Items.RemoveAt(list_Camera_Ip.Items.IndexOf(list_Camera_Ip.SelectedItem));

            //Ajout du nouvel élément
            list_Camera_Ip.Items.Add("" + Nom + "");

        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            string nameCam = "";
            Camera camCk;
            CheckBox ck = sender as CheckBox;
            if ((bool)ck.IsChecked == true)
            {
                nameCam = (sender as CheckBox).Tag.ToString();
                camCk = CameraBLL.Instance.GetCamera_By_Nom(nameCam);
                camCk.came_use = (bool)true;
                CameraBLL.Instance.UpdateCamera(camCk);
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            string nameCam = "";
            Camera camCk;
            CheckBox ck = sender as CheckBox;
            if ((bool)ck.IsChecked == false)
            {
                nameCam = (sender as CheckBox).Tag.ToString();
                camCk = CameraBLL.Instance.GetCamera_By_Nom(nameCam);
                camCk.came_use = (bool)false;
                CameraBLL.Instance.UpdateCamera(camCk);
            }
        }

        private void ckList_Initialized(object sender, EventArgs e)
        {
            listCk.Add(sender as CheckBox);
        }

        private void list_Camera_Ip_Loaded(object sender, RoutedEventArgs e)
        {
            List<Camera> listCams = CameraBLL.Instance.GetCameras();
            foreach (Camera myCam in listCams)
            {
                foreach (CheckBox ck in listCk)
                {
                    if ((string)ck.Tag == (string)myCam.came_nom)
                    {
                        ck.IsChecked = (bool)myCam.came_use;
                        break;
                    }
                }
            }
        }
        #endregion

        #region gestion mail
        private void button_Annuler_Config_Mail_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void button_Valider_Config_Mail_Click(object sender, RoutedEventArgs e)
        {
            int id_pour_update = 0;
            Config Configmail = new Config();

            List<Config> listConfig = ConfigBLL.Instance.GetConfigs();
            if (listConfig.Count > 0)
            {
                foreach (Config myConfig in listConfig)
                {
                    id_pour_update = myConfig.conf_id;
                    Configmail = myConfig;
                }
            }

            Configmail.conf_fn_mail = textBox_Adresse_Emission.Text;
            Configmail.conf_fn_log = textBox_Login_SMTP.Text;
            Configmail.conf_fn_pwd = textBox_Pass_SMTP.Password;
            Configmail.conf_fn_serv = textBox_Serveur_SMTP.Text;

            ConfigBLL.Instance.UpdateConfig(Configmail);

        }
        #endregion

        #region gestion utilisateurs
        //on recupere l'utilisateur selectionné et on remplie les champs.
        private void listView_User_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                List<int> Tab_Image = new List<int>();
                if (listView_User.SelectedItem == null)
                {
                }
                else
                {
                    String Nom_User_List = listView_User.SelectedItem.ToString();

                    //on récupère l'Id de la caméra dans la table
                    User UnUsr = UserBLL.Instance.GetUser_By_Nom(Nom_User_List);

                    //textBox_Nom_Utilisateur.Text= UnUsr.user_name;
                    int Index_espace = UnUsr.user_name.IndexOf(" ");
                    textBox_Nom_Utilisateur.Text = UnUsr.user_name.Substring(0, Index_espace);
                    // textBox1_Prenom_Utilisateur.Text= UnUsr.user_name;
                    int test = UnUsr.user_name.Length - (Index_espace + 1);
                    textBox1_Prenom_Utilisateur.Text = UnUsr.user_name.Substring(Index_espace + 1, test);

                    textBoxe_mail.Text = UnUsr.user_mail;
                    textBox_Telephone.Text = UnUsr.user_tel;
                    textBox_Login.Text = UnUsr.user_login;
                    textBox_Pwd.Password = UnUsr.user_pwd;
                    comboBox_Role.SelectedItem = ((ComboBoxItem)comboBox_Role.Items[(int)UnUsr.user_role - 1]);
                    comboBox_Lvl_Notif.SelectedItem = ((ComboBoxItem)comboBox_Lvl_Notif.Items[(int)UnUsr.user_lvl_notif - 1]);
                }



            }
            catch (Exception ex)
            {
                MessageBox.Show("listView_User_SelectionChanged: " + ex.Message);
            }

        }

        private void button_Ajouter_Config_Utilisateur_Click(object sender, RoutedEventArgs e)
        {

            String Nom_User = "" + textBox1_Prenom_Utilisateur.Text + " " + textBox_Nom_Utilisateur.Text + "";
            try
            {
                //on récupère l'Id de la caméra dans la table
                User UnUsr = UserBLL.Instance.GetUser_By_Nom(Nom_User);

                if (UnUsr.user_name == Nom_User)
                {
                    label_Confirmation.Text = "L'utilisateur existe déja";
                    this.label_Confirmation.Foreground = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    User objUser = new User();

                    objUser.user_name = "" + textBox1_Prenom_Utilisateur.Text + " " + textBox_Nom_Utilisateur.Text + "";
                    objUser.user_role = Convert.ToInt32(comboBox_Role.Text);
                    objUser.user_lvl_notif = Convert.ToInt32(comboBox_Lvl_Notif.Text);
                    objUser.user_mail = textBoxe_mail.Text;
                    objUser.user_tel = textBox_Telephone.Text;
                    objUser.user_login = textBox_Login.Text;
                    objUser.user_pwd = textBox_Pwd.Password;


                    try
                    {
                        UserBLL.Instance.AddUser(objUser);//ajoute l'objet en base

                        listView_User.Items.Add("" + objUser.user_name + "");

                        label_Confirmation.Text = "Ajout de l'utilisateur réussi";
                        this.label_Confirmation.Foreground = new SolidColorBrush(Colors.Green);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("button_Ajouter_Config_Utilisateur_Click: " + ex.Message);
                        label_Confirmation.Text = "Ajout de l'utilisateur à échoué";
                        this.label_Confirmation.Foreground = new SolidColorBrush(Colors.Red);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("button_Ajouter_Config_Utilisateur_Click: " + ex.Message);
                label_Confirmation.Text = "Ajout de l'utilisateur à échoué";
                this.label_Confirmation.Foreground = new SolidColorBrush(Colors.Red);
            }



        }

        private void button_Supprimer_Config_Utilisateur_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                String Nom_User_List = listView_User.SelectedItem.ToString();
                UserBLL.Instance.RemoveUser_By_Nom(Nom_User_List);

                listView_User.Items.RemoveAt(listView_User.SelectedIndex);

                label_Confirmation.Text = "Suppression de l'utilisateur réussi";
                this.label_Confirmation.Foreground = new SolidColorBrush(Colors.Green);

                //On remet les champs à 0
                textBox_Nom_Utilisateur.Text = "";
                textBox1_Prenom_Utilisateur.Text = "";
                textBoxe_mail.Text = "";
                textBox_Telephone.Text = "";
                textBox_Login.Text = "";
                textBox_Pwd.Password = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show("button_Supprimer_Config_Utilisateur_Click: " + ex.Message);
                label_Confirmation.Text = "Suppression de l'utilisateur à échoué";
                this.label_Confirmation.Foreground = new SolidColorBrush(Colors.Red);
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            textBox_Nom_Utilisateur.Text = "";
            textBox1_Prenom_Utilisateur.Text = "";
            textBoxe_mail.Text = "";
            textBox_Telephone.Text = "";
            textBox_Login.Text = "";
            textBox_Pwd.Password = "";
        }

        private void button_Modifier_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                String Nom_User_List = listView_User.SelectedItem.ToString();
                User UnUsr = UserBLL.Instance.GetUser_By_Nom(Nom_User_List);


                User objUser = new User();

                objUser.user_name = "" + textBox1_Prenom_Utilisateur.Text + " " + textBox_Nom_Utilisateur.Text + "";
                objUser.user_role = Convert.ToInt32(comboBox_Role.Text);
                objUser.user_lvl_notif = Convert.ToInt32(comboBox_Lvl_Notif.Text);
                objUser.user_mail = textBoxe_mail.Text;
                objUser.user_tel = textBox_Telephone.Text;
                objUser.user_login = textBox_Login.Text;
                objUser.user_pwd = textBox_Pwd.Password;
                objUser.user_id = UnUsr.user_id;


                UserBLL.Instance.UpdateUser(objUser);
                //listView_User.SelectedValue = "" + textBox_Nom_Utilisateur.Text + " " + textBox1_Prenom_Utilisateur.Text + "";


                label_Confirmation.Text = "Modification de l'utilisateur réussi";
                this.label_Confirmation.Foreground = new SolidColorBrush(Colors.Green);


            }
            catch (Exception ex)
            {
                MessageBox.Show("button_Modifier_Click: " + ex.Message);
                label_Confirmation.Text = "Modification de l'utilisateur à échoué";
                this.label_Confirmation.Foreground = new SolidColorBrush(Colors.Red);
            }
        }
        private void Recuperer_Tout_User_Dans_Base()
        {
            List<User> listUsr = UserBLL.Instance.GetUsers();
            foreach (User myUsr in listUsr)
            {
                listView_User.Items.Add("" + myUsr.user_name + "");
                a++;

            }
        }
        #endregion

        #region gestion planification

        public ObservableCollection<User> ListUser
        {
            get { return listUser; }
        }

        private void listUsers_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.LeftButton == MouseButtonState.Pressed && listUsers.SelectedItem != null)
                {
                    // Get the dragged ListViewItem
                    ListView listUser = sender as ListView;
                    ListViewItem listViewItem =
                        FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);

                    // Find the data behind the ListViewItem
                    User user = (User)listUsers.ItemContainerGenerator.
                        ItemFromContainer(listViewItem);

                    // Initialize the drag & drop operation
                    DataObject dragData = new DataObject("myFormat", user);
                    DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Copy);
                }
            }
            catch { }
        }

        private static T FindAnchestor<T>(DependencyObject current)
         where T : DependencyObject
        {
            do
            {
                if (current is T)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            }
            while (current != null);
            return null;
        }

        private void listSchedule_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("myFormat"))
            {
                e.Effects = DragDropEffects.Copy;
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
        }

        private void listSchedule_Drop(object sender, DragEventArgs e)
        {
            User contact = e.Data.GetData("myFormat") as User;

            ListView listDrag = new ListView();
            listDrag = sender as ListView;
            switch (listDrag.Name)
            {
                case "lundi1":
                    lundi1.Items.Clear();
                    lundi1.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(11);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "mardi1":
                    mardi1.Items.Clear();
                    mardi1.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(21);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "mercredi1":
                    mercredi1.Items.Clear();
                    mercredi1.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(31);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "jeudi1":
                    jeudi1.Items.Clear();
                    jeudi1.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(41);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "vendredi1":
                    vendredi1.Items.Clear();
                    vendredi1.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(51);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "samedi1":
                    samedi1.Items.Clear();
                    samedi1.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(61);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "dimanche1":
                    dimanche1.Items.Clear();
                    dimanche1.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(71);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "lundi2":
                    lundi2.Items.Clear();
                    lundi2.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(12);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "mardi2":
                    mardi2.Items.Clear();
                    mardi2.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(22);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "mercredi2":
                    mercredi2.Items.Clear();
                    mercredi2.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(32);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "jeudi2":
                    jeudi2.Items.Clear();
                    jeudi2.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(42);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "vendredi2":
                    vendredi2.Items.Clear();
                    vendredi2.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(52);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "samedi2":
                    samedi2.Items.Clear();
                    samedi2.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(62);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "dimanche2":
                    dimanche2.Items.Clear();
                    dimanche2.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(72);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;

                case "lundi3":
                    lundi3.Items.Clear();
                    lundi3.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(13);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "mardi3":
                    mardi3.Items.Clear();
                    mardi3.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(23);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "mercredi3":
                    mercredi3.Items.Clear();
                    mercredi3.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(33);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "jeudi3":
                    jeudi3.Items.Clear();
                    jeudi3.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(43);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "vendredi3":
                    vendredi3.Items.Clear();
                    vendredi3.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(53);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "samedi3":
                    samedi3.Items.Clear();
                    samedi3.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(63);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                case "dimanche3":
                    dimanche3.Items.Clear();
                    dimanche3.Items.Add(contact.user_login);
                    sche = ScheduleBLL.Instance.GetSchedule(73);
                    sche.user_id = contact.user_id;
                    ScheduleBLL.Instance.UpdateSchedule(sche);
                    break;
                default:
                    break;
            }
        }

        private void listUsers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listUsers.Items.Count != 0)
            {
                User user = (User)listUsers.Items[listUsers.SelectedIndex];
                String nameUser = user.user_login;

                foreach (ListView lv in listLv)
                {
                    if (lv.Items.Count != 0)
                    {
                        if (lv.Items[0].ToString() == nameUser)
                        {
                            lv.SelectedIndex = 0;
                        }
                    }
                }
            }
        }

        private void tabPlanifConf_Initialized(object sender, EventArgs e)
        {
            User tmpUser = new User();
            //ajout user dans listview planification
            listUser = new ObservableCollection<User>();
            sche = new Schedule();

            // Assign this collection to ItemsSource property of ListView

            listUsers.ItemsSource = listUser;

            // Start adding items to the collection
            // They automatically get added to ListView without a need to write any extra code
            List<User> listTmp = UserBLL.Instance.GetUsers();
            foreach (User myUser in listTmp)
            {
                listUser.Add(myUser);

            }

            //Initialisation du tableau de l'emploi du temps
            List<Schedule> listScheInit = ScheduleBLL.Instance.GetSchedules();
            foreach (Schedule tmpSche in listScheInit)
            {
                tmpUser = UserBLL.Instance.GetUser(tmpSche.user_id);
                switch (tmpSche.sche_id)
                {
                    case 11:
                        lundi1.Items.Clear();
                        lundi1.Items.Add(tmpUser.user_login);
                        break;
                    case 21:
                        mardi1.Items.Clear();
                        mardi1.Items.Add(tmpUser.user_login);
                        break;
                    case 31:
                        mercredi1.Items.Clear();
                        mercredi1.Items.Add(tmpUser.user_login);

                        break;
                    case 41:
                        jeudi1.Items.Clear();
                        jeudi1.Items.Add(tmpUser.user_login);

                        break;
                    case 51:
                        vendredi1.Items.Clear();
                        vendredi1.Items.Add(tmpUser.user_login);

                        break;
                    case 61:
                        samedi1.Items.Clear();
                        samedi1.Items.Add(tmpUser.user_login);

                        break;
                    case 71:
                        dimanche1.Items.Clear();
                        dimanche1.Items.Add(tmpUser.user_login);

                        break;
                    case 12:
                        lundi2.Items.Clear();
                        lundi2.Items.Add(tmpUser.user_login);

                        break;
                    case 22:
                        mardi2.Items.Clear();
                        mardi2.Items.Add(tmpUser.user_login);

                        break;
                    case 32:
                        mercredi2.Items.Clear();
                        mercredi2.Items.Add(tmpUser.user_login);

                        break;
                    case 42:
                        jeudi2.Items.Clear();
                        jeudi2.Items.Add(tmpUser.user_login);

                        break;
                    case 52:
                        vendredi2.Items.Clear();
                        vendredi2.Items.Add(tmpUser.user_login);

                        break;
                    case 62:
                        samedi2.Items.Clear();
                        samedi2.Items.Add(tmpUser.user_login);

                        break;
                    case 72:
                        dimanche2.Items.Clear();
                        dimanche2.Items.Add(tmpUser.user_login);

                        break;

                    case 13:
                        lundi3.Items.Clear();
                        lundi3.Items.Add(tmpUser.user_login);

                        break;
                    case 23:
                        mardi3.Items.Clear();
                        mardi3.Items.Add(tmpUser.user_login);

                        break;
                    case 33:
                        mercredi3.Items.Clear();
                        mercredi3.Items.Add(tmpUser.user_login);

                        break;
                    case 43:
                        jeudi3.Items.Clear();
                        jeudi3.Items.Add(tmpUser.user_login);

                        break;
                    case 53:
                        vendredi3.Items.Clear();
                        vendredi3.Items.Add(tmpUser.user_login);

                        break;
                    case 63:
                        samedi3.Items.Clear();
                        samedi3.Items.Add(tmpUser.user_login);

                        break;
                    case 73:
                        dimanche3.Items.Clear();
                        dimanche3.Items.Add(tmpUser.user_login);

                        break;
                    default:
                        break;
                }
            }


        }
        private void tabPlanifConf_Initialized(object sender, MouseButtonEventArgs e)
        {
            sche = new Schedule();
            User tmpUser = new User();
            List<User> listTmp = UserBLL.Instance.GetUsers();
            listUser.Clear();
            foreach (User myUser in listTmp)
            {
                listUser.Add(myUser);

            }

            //Initialisation du tableau de l'emploi du temps
            List<Schedule> listScheInit = ScheduleBLL.Instance.GetSchedules();
            foreach (Schedule tmpSche in listScheInit)
            {
                tmpUser = UserBLL.Instance.GetUser(tmpSche.user_id);
                switch (tmpSche.sche_id)
                {
                    case 11:
                        lundi1.Items.Clear();
                        lundi1.Items.Add(tmpUser.user_login);
                        break;
                    case 21:
                        mardi1.Items.Clear();
                        mardi1.Items.Add(tmpUser.user_login);
                        break;
                    case 31:
                        mercredi1.Items.Clear();
                        mercredi1.Items.Add(tmpUser.user_login);

                        break;
                    case 41:
                        jeudi1.Items.Clear();
                        jeudi1.Items.Add(tmpUser.user_login);

                        break;
                    case 51:
                        vendredi1.Items.Clear();
                        vendredi1.Items.Add(tmpUser.user_login);

                        break;
                    case 61:
                        samedi1.Items.Clear();
                        samedi1.Items.Add(tmpUser.user_login);

                        break;
                    case 71:
                        dimanche1.Items.Clear();
                        dimanche1.Items.Add(tmpUser.user_login);

                        break;
                    case 12:
                        lundi2.Items.Clear();
                        lundi2.Items.Add(tmpUser.user_login);

                        break;
                    case 22:
                        mardi2.Items.Clear();
                        mardi2.Items.Add(tmpUser.user_login);

                        break;
                    case 32:
                        mercredi2.Items.Clear();
                        mercredi2.Items.Add(tmpUser.user_login);

                        break;
                    case 42:
                        jeudi2.Items.Clear();
                        jeudi2.Items.Add(tmpUser.user_login);

                        break;
                    case 52:
                        vendredi2.Items.Clear();
                        vendredi2.Items.Add(tmpUser.user_login);

                        break;
                    case 62:
                        samedi2.Items.Clear();
                        samedi2.Items.Add(tmpUser.user_login);

                        break;
                    case 72:
                        dimanche2.Items.Clear();
                        dimanche2.Items.Add(tmpUser.user_login);

                        break;

                    case 13:
                        lundi3.Items.Clear();
                        lundi3.Items.Add(tmpUser.user_login);

                        break;
                    case 23:
                        mardi3.Items.Clear();
                        mardi3.Items.Add(tmpUser.user_login);

                        break;
                    case 33:
                        mercredi3.Items.Clear();
                        mercredi3.Items.Add(tmpUser.user_login);

                        break;
                    case 43:
                        jeudi3.Items.Clear();
                        jeudi3.Items.Add(tmpUser.user_login);

                        break;
                    case 53:
                        vendredi3.Items.Clear();
                        vendredi3.Items.Add(tmpUser.user_login);

                        break;
                    case 63:
                        samedi3.Items.Clear();
                        samedi3.Items.Add(tmpUser.user_login);

                        break;
                    case 73:
                        dimanche3.Items.Clear();
                        dimanche3.Items.Add(tmpUser.user_login);

                        break;
                    default:
                        break;
                }
            }
        }
        #endregion

        #region Fenêtre principale

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

        /// <summary>
        /// Starts the capture.
        /// </summary>
        private void startCapture()
        {

            CaptureIsStarted = true;
            try
            {

                // Ajout des cam enable dans la liste de caméras dans l'IHM
                List<Camera> listCams = CameraBLL.Instance.GetCamerasEnabled();

                //Ajout des cam enable
                foreach (Camera myCam in listCams)
                {
                    addNewCamera(myCam.came_id, myCam.came_url, myCam.came_nom);
                }

                foreach (CameraFromMjpegDecoder camera in FormsRecognitionManager.Instance.listCamera)
                {

                    // Récupération des images a détecter pour cette camera
                    List<Image_Haar> HaartainningFiles = new List<Image_Haar>();
                    List<CameraImage_Haar> listCameraImage_Haar = CameraImage_HaarBLL.Instance.GetCameraImage_HaarsOfCamera(camera.CameraId);

                    if (listCameraImage_Haar.Count <= 0)
                        return;

                    foreach (CameraImage_Haar cameraImage_Haar in listCameraImage_Haar)
                    {
                        Image_Haar image_Haar = Image_HaarBLL.Instance.GetImage_Haar(cameraImage_Haar.Image_Haar_imha_id);

                        if (File.Exists(image_Haar.imha_fn))
                        {
                            HaartainningFiles.Add(image_Haar);
                        }
                    }
                    camera.HaartainningFilesListe = HaartainningFiles;
                    ProcessCam(camera);
                }
            }
            catch (Exception ex)
            {
                _Log.Debug(ex);
            }

        }

        /// <summary>
        /// Stops the capture.
        /// </summary>
        private void stopCapture()
        {
            CaptureIsStarted = false;


            //clear de la liste
            ListCam.Items.Clear();

            if (FormsRecognitionManager.Instance.listCamera == null)
                return;

            // remove event handler
            foreach (CameraFromMjpegDecoder camera in FormsRecognitionManager.Instance.listCamera)
            {
                camera.NewFrameFromCamEvent -= FramFromCamManager.Instance.NewFrameAllowFromCamera;
            }
        }

        /// <summary>
        /// Detects the object.
        /// </summary>
        /// <param name="param">The param.</param>
        public void ProcessCam(object param)
        {
            try
            {
                CameraFromMjpegDecoder camera = param as CameraFromMjpegDecoder;
                camera.NewFrameFromCamEvent += FramFromCamManager.Instance.NewFrameAllowFromCamera;
            }
            catch (Exception ex)
            {
                _Log.Fatal("DetectObject: Exception: " + ex);
            }

        }

        /// <summary>
        /// Adds the new camera.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="camPath">The cam path.</param>
        private void addNewCamera(int id, string camPath, string camName)
        {
            if (id < 0) return;
            if (String.IsNullOrEmpty(camPath)) return;

            try
            {

                _Log.DebugFormat("addNewCamera(int {0}, string {1}, string {2}", id, camPath, camName);
                FormsRecognitionManager.Instance.AddNewCamera(id, camPath);

                System.Windows.Controls.Image imageCam = new System.Windows.Controls.Image();
                imageCam.Tag = id;
                imageCam.Height = 80;
                imageCam.Width = 120;
                imageCam.Stretch = Stretch.Uniform;
                imageCam.ToolTip = camName;


                ListCam.Items.Add(imageCam);
                ListCam.SelectionChanged += new SelectionChangedEventHandler(ListCam_SelectionChanged);

            }
            catch (Exception ex)
            {

                _Log.WarnFormat("addNewCamera(int {0}, string {1}): Exception {2}", id, camPath, ex);
            }
        }

        void ListCam_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            ListView list = sender as ListView;
            if (list != null)
            {
                if (list.SelectedIndex < 0)
                    return;

                System.Windows.Controls.Image image = (System.Windows.Controls.Image)list.Items[list.SelectedIndex];

                if (image != null)
                {
                    SelectedCam = (int)image.Tag;
                    //get the cam with the tag(id)
                    Camera camSel = CameraBLL.Instance.GetCamera(SelectedCam);
                    txtNameCam.Text = camSel.came_nom;
                    txtDescCam.Text = camSel.came_desc;
                    txtLocCam.Text = camSel.came_loc;
                    txtIpCam.Text = camSel.came_url;
                    //get objects detected by this cam
                    List<CameraImage_Haar> listHaar = CameraImage_HaarBLL.Instance.GetCameraImage_HaarsOfCamera(SelectedCam);
                    stackCamHaar.Children.Clear();
                    Border tmpB = new Border();
                    Color color = (Color)ColorConverter.ConvertFromString("#FF4C4848");
                    tmpB.BorderBrush = new SolidColorBrush(color);
                    tmpB.BorderThickness = new Thickness(0, 1, 0, 0);
                    stackCamHaar.Children.Add(tmpB);
                    TextBlock tmptxt = new TextBlock();
                    tmptxt.Text = "Objets détectés";
                    tmptxt.FontFamily = new FontFamily("Arial");
                    tmptxt.VerticalAlignment = VerticalAlignment.Center;
                    tmptxt.HorizontalAlignment = HorizontalAlignment.Center;
                    tmptxt.FontSize = 18;
                    tmptxt.TextAlignment = TextAlignment.Center;
                    tmptxt.Padding = new Thickness(0, 2, 0, 2);
                    tmptxt.Margin = new Thickness(0, 10, 0, 10);
                    color = (Color)ColorConverter.ConvertFromString("#FF33383B");
                    tmptxt.Foreground = new SolidColorBrush(color);
                    tmptxt.FontWeight = FontWeights.SemiBold;
                    stackCamHaar.Children.Add(tmptxt);
                    Border tmpBN = new Border();
                    color = (Color)ColorConverter.ConvertFromString("#FF4C4848");
                    tmpBN.BorderBrush = new SolidColorBrush(color);
                    tmpBN.Margin = new Thickness(0, 0, 0, 5);
                    tmpBN.BorderThickness = new Thickness(0, 1, 0, 0);
                    stackCamHaar.Children.Add(tmpBN);
                    foreach (CameraImage_Haar tmpCam in listHaar)
                    {
                        //get the image_haar
                        Image_Haar img = Image_HaarBLL.Instance.GetImage_Haar(tmpCam.Image_Haar_imha_id);
                        TextBlock tmptxt2 = new TextBlock();
                        tmptxt2.Text = img.imha_label;
                        tmptxt2.FontFamily = new FontFamily("Arial");
                        tmptxt2.FontSize = 10;
                        tmptxt2.TextAlignment = TextAlignment.Center;
                        tmptxt2.Padding = new Thickness(0, 2, 0, 2);
                        tmptxt2.Margin = new Thickness(0, 0, 0, 0);
                        stackCamHaar.Children.Add(tmptxt2);
                    }
                }
            }
        }

        private void tabCam_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (ListCam != null)
            {
                    if (SelectedCam != -1)
                    {
                        //get the cam with the tag(id)
                        Camera camSel = CameraBLL.Instance.GetCamera(SelectedCam);
                        txtNameCam.Text = camSel.came_nom;
                        txtDescCam.Text = camSel.came_desc;
                        txtLocCam.Text = camSel.came_loc;
                        txtIpCam.Text = camSel.came_url;
                        //get objects detected by this cam
                        List<CameraImage_Haar> listHaar = CameraImage_HaarBLL.Instance.GetCameraImage_HaarsOfCamera(SelectedCam);
                        stackCamHaar.Children.Clear();
                        Border tmpB = new Border();
                        Color color = (Color)ColorConverter.ConvertFromString("#FF4C4848");
                        tmpB.BorderBrush = new SolidColorBrush(color);
                        tmpB.BorderThickness = new Thickness(0, 1, 0, 0);
                        stackCamHaar.Children.Add(tmpB);
                        TextBlock tmptxt = new TextBlock();
                        tmptxt.Text = "Objets détectés";
                        tmptxt.FontFamily = new FontFamily("Arial");
                        tmptxt.VerticalAlignment = VerticalAlignment.Center;
                        tmptxt.HorizontalAlignment = HorizontalAlignment.Center;
                        tmptxt.FontSize = 18;
                        tmptxt.TextAlignment = TextAlignment.Center;
                        tmptxt.Padding = new Thickness(0, 2, 0, 2);
                        tmptxt.Margin = new Thickness(0, 10, 0, 10);
                        color = (Color)ColorConverter.ConvertFromString("#FF33383B");
                        tmptxt.Foreground = new SolidColorBrush(color);
                        tmptxt.FontWeight = FontWeights.SemiBold;
                        stackCamHaar.Children.Add(tmptxt);
                        Border tmpBN = new Border();
                        color = (Color)ColorConverter.ConvertFromString("#FF4C4848");
                        tmpBN.BorderBrush = new SolidColorBrush(color);
                        tmpBN.Margin = new Thickness(0, 0, 0, 5);
                        tmpBN.BorderThickness = new Thickness(0, 1, 0, 0);
                        stackCamHaar.Children.Add(tmpBN);
                        foreach (CameraImage_Haar tmpCam in listHaar)
                        {
                            //get the image_haar
                            Image_Haar img = Image_HaarBLL.Instance.GetImage_Haar(tmpCam.Image_Haar_imha_id);
                            TextBlock tmptxt2 = new TextBlock();
                            tmptxt2.Text = img.imha_label;
                            tmptxt2.FontFamily = new FontFamily("Arial");
                            tmptxt2.FontSize = 10;
                            tmptxt2.TextAlignment = TextAlignment.Center;
                            tmptxt2.Padding = new Thickness(0, 2, 0, 2);
                            tmptxt2.Margin = new Thickness(0, 0, 0, 0);
                            stackCamHaar.Children.Add(tmptxt2);
                        }
                    }
                
            }
        }

       

        private object LongTimeMethod()
        {
            return null;
        }

        private void CallBackUpdateCameraDetectionSenderEvent(object nullObject, ProcessDetectEventArgs pDetectEventArgs)
        {

            System.Threading.Thread thread = new System.Threading.Thread(
     new System.Threading.ThreadStart(
       delegate()
       {
           this.Dispatcher.Invoke(
             System.Windows.Threading.DispatcherPriority.ApplicationIdle,
             new Action(
               delegate()
               {
                   try
                   {
                       //_Log.Debug("new event UpdateCameraDetectionSenderEvent !!!");

                       ImageSource imageSource = null;
                       if (!pDetectEventArgs.detectObject)
                           imageSource = ImageHelper.CreateBitmapSourceFromBitmap(pDetectEventArgs.bitmapSource);
                       else
                           imageSource = ImageHelper.CreateBitmapSourceFromBitmap(pDetectEventArgs.bitmapFromdetection);


                       foreach (System.Windows.Controls.Image imageCamera in ListCam.Items)
                       {
                           if (pDetectEventArgs.camId == (int)imageCamera.Tag)
                           {
                               imageCamera.Source = imageSource;

                               if (SelectedCam == pDetectEventArgs.camId)
                               {
                                   //Thread UpdateUI = new Thread(UpdateCameraFrame);
                                   //UpdateUI.Start(detectEventArgs);
                                   imageBoxSelectedCam.Source = imageSource;
                               }

                               // Forcing the CommandManager to raise the RequerySuggested event

                           }
                       }
                   }
                   catch (Exception ex)
                   {
                       _Log.Fatal("CallBackUpdateCameraDetectionSenderEvent: Exception: " + ex);
                   }
               }
           ));
       }
   ));

            thread.Start();


            //Application.Current.Dispatcher.Invoke(new Action(() =>
            // UIThreadHelper.UIThread(this, new Action(() =>
            {


                // Application.Current.Dispatcher.Invoke(new Action(() =>
                {

                }
                //));
            }
            //));

            //Update code goes in here
            //});
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            foreach (CameraFromMjpegDecoder camObj in FormsRecognitionManager.Instance.listCamera)
            {
                camObj.UnregisterListenner();
            }
            FormsRecognitionManager.Instance.listCamera = new List<CameraFromMjpegDecoder>();


            FormsRecognitionManager.Instance.closeAllAlert();


        }

        private void checkBoxDetectObject_Checked(object sender, RoutedEventArgs e)
        {


            foreach (CameraFromMjpegDecoder camera in FormsRecognitionManager.Instance.listCamera)
            {
                camera.detectObject = (bool)checkBoxDetectObject.IsChecked;
            }

        }

        private void checkBoxDetectObject_Unchecked(object sender, RoutedEventArgs e)
        {
            foreach (CameraFromMjpegDecoder camera in FormsRecognitionManager.Instance.listCamera)
            {
                camera.detectObject = (bool)checkBoxDetectObject.IsChecked;
            }

            //if (!(bool)checkBoxDetectObject.IsChecked)
            //{
            //    FormsRecognitionManager.Instance.closeAllAlert();
            //}
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            //storyboard = this.TryFindResource("ButtonStoryBoard") as Storyboard;

            //if (!_started)
            //{

            //    if (storyboard != null)
            //    {
            //        storyboard.Begin(btnStart, true);

            //    }

            //    _started = true;
            //    btnStart.Content = "Stop";
            //}
            //else
            //{
            //    _started = false;

            //    if (storyboard != null)
            //    {
            //        storyboard.Stop(btnStart);
            //    }


            //    btnStart.Content = "Start";
            //}
        }

        private void tabItemStats_Loaded(object sender, RoutedEventArgs e)
        {
            majStats();
        }

        private void majStats()
        {
            try
            {
                double duration = 0;
                List<Alert> lstAlert = new List<Alert>();
                lstStats.Clear();
                lstAlert = AlertBLL.Instance.GetAlertSortByDate();
                foreach (Alert tmpAlert in lstAlert)
                {
                    //recupérer durée de la vidéo pour en sortir la durée de l'alerte
                    Video tmpVid = VideoBLL.Instance.GetVideo((int)tmpAlert.vide_id);
                    GetVideoLength(tmpVid.vide_fn, out duration);
                    //récupérer la caméra
                    Camera tmpCam = CameraBLL.Instance.GetCamera((int)tmpAlert.came_id);
                    //récupérer l'utilisateur
                    User tmpUser = UserBLL.Instance.GetUser((int)tmpAlert.user_id);
                    //récupérer l'objet détecté
                    Image_Details imgDet = Image_DetailsBLL.Instance.GetImage_Details((int)tmpAlert.imde_id);
                    Image_Haar ImgHaar = Image_HaarBLL.Instance.GetImage_Haar((int)imgDet.imha_id);
                    StatsData sData = new StatsData((string)tmpAlert.aler_dt.Value.ToShortDateString(), (string)tmpAlert.aler_dt.Value.ToShortTimeString(), (string)tmpUser.user_name, (string)tmpCam.came_nom, (string)tmpCam.came_loc, (string)tmpCam.came_desc, (string)tmpAlert.aler_lvl.ToString(), duration.ToString(), (string)ImgHaar.imha_label);
                    lstStats.Add(sData);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw new Exception();
            }
        }

        static public bool GetVideoLength(string fileName, out double length)
        {
            DirectShowLib.FilterGraph graphFilter = new DirectShowLib.FilterGraph();
            DirectShowLib.IGraphBuilder graphBuilder;
            DirectShowLib.IMediaPosition mediaPos;
            length = 0.0;

            try
            {
                graphBuilder = (DirectShowLib.IGraphBuilder)graphFilter;
                graphBuilder.RenderFile(fileName, null);
                mediaPos = (DirectShowLib.IMediaPosition)graphBuilder;
                mediaPos.get_Duration(out length);
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                mediaPos = null;
                graphBuilder = null;
                graphFilter = null;
            }
        }


        #endregion

        #region manage MainWindow bar (minimize,maximize,close)
        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg,
                int wParam, int lParam);

        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        public void move_window(object sender, MouseButtonEventArgs e)
        {

            ReleaseCapture();
            SendMessage(new WindowInteropHelper(this).Handle,
                WM_NCLBUTTONDOWN, HT_CAPTION, 0);



        }

        public void EXIT(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        public void MINIMIZE(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;

        }

        public void MAX_RESTORE(object sender, MouseButtonEventArgs e)
        {
            if (this.WindowState == WindowState.Normal)
                this.WindowState = WindowState.Maximized;
            else
                this.WindowState = WindowState.Normal;
        }

        public void EnterMin(object sender, MouseEventArgs e)
        {
            (sender as Image).Opacity = 0.7;
        }

        public void LeaveMin(object sender, MouseEventArgs e)
        {
            (sender as Image).Opacity = 0.3;
        }

        public void EnterMax(object sender, MouseEventArgs e)
        {

            (sender as Image).Opacity = 0.7;

        }

        public void LeaveMax(object sender, MouseEventArgs e)
        {
            (sender as Image).Opacity = 0.3;
        }

        public void EnterClose(object sender, MouseEventArgs e)
        {
            (sender as Image).Opacity = 0.7;

        }

        public void LeaveClose(object sender, MouseEventArgs e)
        {
            (sender as Image).Opacity = 0.3;
        }

        #endregion

        #region Gestion config HAAR
        /// <summary>
        /// Handles the SelectionChanged event of the list_HarrFiles control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="SelectionChangedEventArgs" /> instance containing the event data.</param>
        private void list_HarrFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_listHaarObjects == null)
                return;
            if (list_HarrFiles.SelectedItem != null)
            {
                SetHaarObjectSelected(list_HarrFiles.SelectedIndex);
            }

            if (camDecoderForTestHaarObjects != null)
            {
                // Récupération des images a détecter pour cette camera
                List<Image_Haar> HaartainningFiles = new List<Image_Haar>();

                Image_Haar imageHaar = _listHaarObjects[list_HarrFiles.SelectedIndex];
                if (imageHaar == null)
                    return;
                
                //RAZ liste
                camDecoderForTestHaarObjects.HaartainningFilesListe.Clear();              

                camDecoderForTestHaarObjects.HaartainningFilesListe.Add(imageHaar);
            }
        }

        /// <summary>
        /// Sliders the scal factor_ value changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void SliderScalFactor_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            TextBox_Haar_ScaleFactor_Value.Text = String.Format("{0:0.0}", SliderScalFactor.Value);
        }

        /// <summary>
        /// Sliders the min neighbors_ value changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void SliderMinNeighbors_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            TextBox_Haar_neightboors_Value.Text = String.Format("{0:0.0}", SliderMinNeighbors.Value);
        }

        /// <summary>
        /// Handles the Click event of the button_Ajouter_Fichier_Haar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void button_Ajouter_Fichier_Haar_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".xml";
            dlg.Filter = "Haarcascade Files (.xml)|*.xml";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // test desc fileName
            if (String.IsNullOrEmpty(TextBox_Haar_File_Description.Text))
            {
                MessageBox.Show("Le fichier doit obligatoirement comporter une description, merci de la saisir!");
                TextBox_Haar_File_Description.Focus();
                return;
            }

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;

                AddHaarCascadeFileInBDD(filename, TextBox_Haar_File_Nom.Text, TextBox_Haar_File_Description.Text);
            }
        }

        /// <summary>
        /// Adds the haar cascade file in BDD.
        /// </summary>
        /// <param name="filename">The filename.</param>
        private void AddHaarCascadeFileInBDD(string filename, string haarName, string haarDescription)
        {
            // set new HaarCascadeFile
            Image_Haar newImageHaar = new Image_Haar();
            newImageHaar.imha_fn = filename;
            newImageHaar.imha_label = haarName;
            newImageHaar.imha_desc = haarDescription;
            newImageHaar.imha_height = 20;
            newImageHaar.imha_width = 20;
            newImageHaar.imha_scaleFactor = 1.1;
            newImageHaar.imha_minNeighbors = 10;

            // Insertion en BDD
            Image_HaarBLL.Instance.AddImage_Haar(newImageHaar);

            // Update list Haar
            InitialisHaarObjects();

            // show values
            SetHaarObjectSelected(_listHaarObjects.Count - 1);

            // clear text description
            TextBox_Haar_File_Nom.Text = String.Empty;
            TextBox_Haar_File_Description.Text = String.Empty;

        }

        /// <summary>
        /// Initialises the haar objects.
        /// </summary>
        /// <exception cref="System.NotImplementedException"></exception>
        private void InitialisHaarObjects()
        {
            try
            {
                _listHaarObjects = Image_HaarBLL.Instance.GetImage_Haars();

                ArrayList itemsList = new ArrayList();


                foreach (Image_Haar item in _listHaarObjects)
                {
                    itemsList.Add(item.imha_label);
                }

                list_HarrFiles.ItemsSource = itemsList;
            }
            catch (Exception ex)
            {

                MessageBox.Show("Exception: " + ex);
            }
        }

        /// <summary>
        /// Initialises the haar objects.
        /// </summary>
        /// <exception cref="System.NotImplementedException"></exception>
        private void InitialisCameraForHaarTest()
        {
            try
            {
                _listCameraForHaarTest = CameraBLL.Instance.GetCameras();

                ArrayList itemsList = new ArrayList();


                foreach (Camera item in _listCameraForHaarTest)
                {
                    itemsList.Add(item.came_nom);
                }
                comboBox_Haar_Choix_Cam.ItemsSource = itemsList;
            }
            catch (Exception ex)
            {

                MessageBox.Show("Exception: " + ex);
            }
        }

        /// <summary>
        /// Sets the haar object selected.
        /// </summary>
        /// <param name="position">The position.</param>
        private void SetHaarObjectSelected(int position)
        {
            if (_listHaarObjects.Count <= 0)
                return;
            if (position > _listHaarObjects.Count - 1)
                return;

            list_HarrFiles.SelectedIndex = position;

            Image_Haar haarTmp = _listHaarObjects[position];
            TextBox_Haar_File_Height.Text = haarTmp.imha_height.ToString();
            TextBox_Haar_File_Width.Text = haarTmp.imha_width.ToString();

            SliderScalFactor.Value = Convert.ToDouble(haarTmp.imha_scaleFactor);
            SliderMinNeighbors.Value = Convert.ToDouble(haarTmp.imha_minNeighbors);

            //TextBox_Haar_File_Nom.Text = haarTmp.imha_label;
            //TextBox_Haar_File_Description.Text = haarTmp.imha_desc;
        }

        private void button_Update_Fichier_Haar_Click(object sender, RoutedEventArgs e)
        {
            if (_listHaarObjects == null)
                return;
            if (list_HarrFiles.SelectedItem == null)
                return;

            try
            {
                // get in BDD
                Image_Haar imageHaar = _listHaarObjects[list_HarrFiles.SelectedIndex];

                //set values from UI
                imageHaar.imha_height = Convert.ToInt32(TextBox_Haar_File_Height.Text);
                imageHaar.imha_width = Convert.ToInt32(TextBox_Haar_File_Width.Text);
                imageHaar.imha_scaleFactor = Convert.ToDouble(String.Format("{0:0.0}", SliderScalFactor.Value));
                imageHaar.imha_minNeighbors = Convert.ToDouble(String.Format("{0:0.0}", SliderMinNeighbors.Value));

                //update values in BDD
                Image_HaarBLL.Instance.UpdateImage_Haar(imageHaar);

                // show message confirmation
                MessageBox.Show("Image_Haar mise à jours: " + _listHaarObjects[list_HarrFiles.SelectedIndex].imha_label);

                // update liste
                InitialisHaarObjects();


            }
            catch (Exception)
            {

                _Log.Error("button_Update_Fichier_Haar_Loaded Image_Haar: " + _listHaarObjects[list_HarrFiles.SelectedIndex].imha_label);
            }
        }



        /// <summary>
        /// Handles the Checked event of the checkBoxHaarDetectObject control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void checkBoxHaarDetectObject_Checked(object sender, RoutedEventArgs e)
        {
            if (camDecoderForTestHaarObjects == null)
                return;

            camDecoderForTestHaarObjects.detectObject = Convert.ToBoolean(checkBoxHaarDetectObject.IsChecked);
        }

        /// <summary>
        /// Handles the Loaded event of the list_HarrFiles control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void list_HarrFiles_Loaded(object sender, RoutedEventArgs e)
        {
            InitialisHaarObjects();
        }

        /// <summary>
        /// Handles the SelectionChanged event of the comboBox_Haar_Choix_Cam control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="SelectionChangedEventArgs" /> instance containing the event data.</param>
        private void comboBox_Haar_Choix_Cam_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBox_Haar_Choix_Cam.SelectedIndex < 0)
                return;

            if (camDecoderForTestHaarObjects != null)
            {
                camDecoderForTestHaarObjects.NewFrameFromCamEvent -= FramFromCamManager.Instance.NewFrameAllowFromCamera;
                camDecoderForTestHaarObjects = null;
            }

            //get Camera info
            Camera cam = _listCameraForHaarTest[comboBox_Haar_Choix_Cam.SelectedIndex];

            FormsRecognitionManager.Instance.listCamera = new List<CameraFromMjpegDecoder>();

            FormsRecognitionManager.Instance.AddNewCamera(cam.came_id, cam.came_url);

            camDecoderForTestHaarObjects = FormsRecognitionManager.Instance.listCamera[0];

            camDecoderForTestHaarObjects.detectObject = Convert.ToBoolean(checkBoxHaarDetectObject.IsChecked);

            // Récupération des images a détecter pour cette camera
            List<Image_Haar> HaartainningFiles = new List<Image_Haar>();

            if (list_HarrFiles.SelectedIndex < 0)
                return;

            Image_Haar imageHaar = _listHaarObjects[list_HarrFiles.SelectedIndex];
            if (imageHaar == null)
                return;

            HaartainningFiles.Add(imageHaar);

            camDecoderForTestHaarObjects.HaartainningFilesListe = HaartainningFiles;

            camDecoderForTestHaarObjects.isInTestMode = true;

            ProcessCam(camDecoderForTestHaarObjects);


        }

        /// <summary>
        /// Calls the back update camera for haar test event.
        /// </summary>
        /// <param name="nullObject">The null object.</param>
        /// <param name="pDetectEventArgs">The <see cref="ProcessDetectEventArgs" /> instance containing the event data.</param>
        private void CallBackUpdateCameraForHaarTestEvent(object nullObject, ProcessDetectEventArgs pDetectEventArgs)
        {

     //       System.Threading.Thread thread = new System.Threading.Thread(
     //new System.Threading.ThreadStart(
     //  delegate()
     //  {
           this.Dispatcher.Invoke(
             System.Windows.Threading.DispatcherPriority.ApplicationIdle,
             new Action(
               delegate()
               {
                   try
                   {
                       ImageSource imageSource = null;
                       if (!pDetectEventArgs.detectObject)
                           imageSource = ImageHelper.CreateBitmapSourceFromBitmap(pDetectEventArgs.bitmapSource);
                       else
                           imageSource = ImageHelper.CreateBitmapSourceFromBitmap(pDetectEventArgs.bitmapFromdetection);

                       imageBox_Capture_HaarTest.Source = imageSource;
                   }
                   catch (Exception ex)
                   {
                       _Log.Fatal("CallBackUpdateCameraForHaarTestEvent: Exception: " + ex);
                   }
               }
           ));
   //    }
   //));
   //         thread.Start();
        }


        /// <summary>
        /// Updates the frame for current cam haar test.
        /// </summary>
        /// <param name="o">The o.</param>
        /// <param name="e">The <see cref="FrameReadyEventArgs" /> instance containing the event data.</param>
        private void UpdateFrameForCurrentCamHaarTest(object o, FrameReadyEventArgs e)
        {
            if (e == null)
                return;

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                imageBox_Capture_HaarTest.Source = e.BitmapImage;
            }));
        }
        /// <summary>
        /// Handles the Click event of the button_Delete_Fichier_Haar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void button_Delete_Fichier_Haar_Click(object sender, RoutedEventArgs e)
        {
            if (_listHaarObjects == null)
                return;
            if (list_HarrFiles.SelectedItem == null)
                return;

            if (MessageBoxResult.OK == MessageBox.Show(String.Format("Voulez vous supprimer le fichier haarcascade : {0}", _listHaarObjects[list_HarrFiles.SelectedIndex].imha_label), String.Empty, MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel))
            {
                try
                {
                    // remove file
                    Image_Haar imageHaar = _listHaarObjects[list_HarrFiles.SelectedIndex];
                    Image_HaarBLL.Instance.RemoveImage_Haar(imageHaar);

                    // update liste
                    InitialisHaarObjects();

                }
                catch (Exception)
                {

                    _Log.Error("Suppression impossible du fichier " + _listHaarObjects[list_HarrFiles.SelectedIndex].imha_label);
                }
            }
        }

        /// <summary>
        /// Handles the Loaded event of the comboBox_Haar_Choix_Cam control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void comboBox_Haar_Choix_Cam_Loaded(object sender, RoutedEventArgs e)
        {
            InitialisCameraForHaarTest();
        }

        /// <summary>
        /// Handles the IsVisibleChanged event of the tabHaarConf control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs" /> instance containing the event data.</param>
        private void tabHaarConf_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (tabHaarConf.IsVisible)
            {
                FormsRecognitionManager.Instance.UpdateCameraDetectionSenderEvent -= new FormsRecognitionManager.UpdateCameraDetectionSenderEventHandler(CallBackUpdateCameraDetectionSenderEvent);
                FormsRecognitionManager.Instance.UpdateCameraDetectionSenderEvent += new FormsRecognitionManager.UpdateCameraDetectionSenderEventHandler(CallBackUpdateCameraForHaarTestEvent);
            }
            else
            {
                FormsRecognitionManager.Instance.UpdateCameraDetectionSenderEvent -= new FormsRecognitionManager.UpdateCameraDetectionSenderEventHandler(CallBackUpdateCameraForHaarTestEvent);
                if (camDecoderForTestHaarObjects != null)
                {
                    camDecoderForTestHaarObjects.NewFrameFromCamEvent -= FramFromCamManager.Instance.NewFrameAllowFromCamera;
                    camDecoderForTestHaarObjects = null;
                    comboBox_Haar_Choix_Cam.SelectedIndex = -1;
                }
                FormsRecognitionManager.Instance.UpdateCameraDetectionSenderEvent += new FormsRecognitionManager.UpdateCameraDetectionSenderEventHandler(CallBackUpdateCameraDetectionSenderEvent);
            }
        }
        /// <summary>
        /// Handles the IsVisibleChanged event of the dockPanel2 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs" /> instance containing the event data.</param>
        private void dockPanel2_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (dockPanel2.IsVisible)
            {
                if (!CaptureIsStarted)
                    startCapture();
            }
            else
            {
                stopCapture();
            }
        }
        #endregion

       

        

        




















































    }
}
